Technical Q&A JAVA01
Simulated Click on AWT Button


Q: How do I programmatically make my java.awt.Button behave as if it were clicked on by the user?

A: This is typically desired when implementing default buttons and giving feedback that the default button action was performed when the Enter or Return key was pressed. There are other instances where this makes good sense from a user interface standpoint. The Macintosh Runtime for Java (MRJ) has provisions for this behavior built in. To get this behavior you need to pass a key-pressed event to the target button. Here is an example of how this could be achieved:

import
java.awt.Button;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
public class SimulateClick
{
     /**
     * A function to simulate a click on the target button.
     * This will make the button draw as if it had been pressed and
     * released, and the button will fire an Action event as if
     * the button were pressed.
     * For use with the Apple MRJ 2.1 EA3 and later.
     */
    static protected void simulateClick(Button target)
    {
        if (target != null)
        {
            KeyEvent keyEvent =
    new KeyEvent(target, KeyEvent.KEY_PRESSED,
       System.currentTimeMillis(), 0, KeyEvent.VK_ENTER,
       (char)KeyEvent.VK_ENTER);
            target.dispatchEvent(keyEvent);
        }
    }
}
  

[Feb 03 1999]


Developer Documentation | Technical Notes | Development Kits | Sample Code